// 字符串转 16 进制
function strToHex(str) {
    let hex = '';
    for (let i = 0; i < str.length; i++) {
        let charCode = str.charCodeAt(i).toString(16);
        hex += charCode.padStart(2, '0');
    }
    return hex;
}

let str = "Hello, world!";
let hexStr = strToHex(str);
console.log(hexStr); // 输出类似 "48656c6c6f2c20776f726c6421"


// 16 进制转字符串
function hexToStr(hex) {
    let str = '';
    for (let i = 0; i < hex.length; i += 2) {
        // 每两个字符转换为一个字节  
        let byte = parseInt(hex.substr(i, 2), 16);
        str += String.fromCharCode(byte);
    }
    return str;
}

let hexStr = "48656c6c6f2c20776f726c6421";
let str = hexToStr(hexStr);
console.log(str); // 输出 "Hello, world!"